package com.qf.controller;

import com.qf.utils.Constants;
import com.sun.xml.internal.bind.v2.runtime.reflect.opt.Const;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String methodStr = req.getParameter(Constants.TAG);
        if(methodStr==null||"".equals(methodStr)){
            methodStr=Constants.INDEX;
        }
        Class clazz= this.getClass();
        try {
            Method method = clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);
            Object result = method.invoke(this, req, resp);
            if(result!=null){
                String jump=(String)result;
                if(jump.startsWith(Constants.FORWARD)){
                    String path = jump.substring(jump.indexOf(Constants.FLAG) + 1);
                    req.getRequestDispatcher(path).forward(req,resp);
                }else if(jump.startsWith(Constants.REDIRECT)){
                    String path = jump.substring(jump.indexOf(Constants.FLAG) + 1);
                    resp.sendRedirect(path);
                }else{
                    resp.getWriter().println(jump);
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}
